package thread;

/**
 * 单个生产者线程和单个消费者线程
 */
public class ProducerAndConsumer {


    public static void main(String[] args) {
        Thread p=new P("A");
        Thread c=new C("A");
        p.start();
        c.start();

    }




}

class P extends Thread{

    private  String lock;

    public P (String lock){
        this.lock=lock;
    }

    public  void setValue(){
        try {
            synchronized (lock){
                if(!ValueObject.value.equals("")){
                    lock.wait();
                }
                String value=System.currentTimeMillis() +"_"+System.nanoTime();
                System.out.println("set的值是"+value);
                ValueObject.value=value;
                lock.notify();
            }

        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
         while (true){
             setValue();
         }
    }
}

class C extends Thread{
    private String lock;

    public C (String lock){
        this.lock=lock;
    }

    public void getValue() {
        try {
            synchronized (lock){
                if(ValueObject.value.equals("")){
                    lock.wait();
                }
                System.out.println("get的值是"+ValueObject.value);
                ValueObject.value="";
                lock.notify();
            }

        }catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            getValue();
        }
    }

}

class ValueObject{
    public  static String value="";
}